<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-row :gutter="10">
        <el-col :span="16">
          <!-- 姓名 -->
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- 手机号码 -->
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- 证件编号 -->
          <el-form-item label="证件编号" prop="idCardNo">
            <el-input
              v-model="queryParams.idCardNo"
              placeholder="请输入证件编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- 证书编号 -->
          <el-form-item label="证书编号" prop="certificateNo">
            <el-input
              v-model="queryParams.certificateNo"
              placeholder="请输入证书编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="16">
          <!-- 有效期起 -->
          <el-form-item label="有效期起" prop="validityStartTime">
            <el-date-picker
              v-model="queryParams.validityStartTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              clearable
              style="width: 210px"
            />
          </el-form-item>

          <!-- 有效期止 -->
          <el-form-item label="有效期止" prop="validityEndTime">
            <el-date-picker
              v-model="queryParams.validityEndTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              clearable
              style="width: 210px"
            />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item style="float: right">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="background-color: #007aff; color: white; border: none"
            >
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              @click="resetQuery"
              style="
                border: 1px solid #ccc;
                background-color: white;
                color: #666;
              "
            >
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="14">
        <!-- 导出 -->
        <el-button plain @click="handleExport">导出</el-button>
        <!-- 证书信息 -->
        <el-button plain @click="openCertificateDialog">证书信息</el-button>

        <!-- 同步证书信息 -->
        <el-button plain @click="handleSyncCertificate">同步证书信息</el-button>

        <!-- 导入证书信息 -->
        <el-button plain @click="handleImportCertificate"
          >导入证书信息</el-button
        >

        <!-- 学员通知 -->
        <el-button plain @click="handleStudentNotice"  :disabled="ids.length ===0">学员通知</el-button>

        <!-- 备注 -->
        <el-button plain @click="handleRemark">备注</el-button>

        <!-- 复审报名 -->
        <!-- <el-button plain @click="handleReviewRegistration">复审报名</el-button> -->
      </el-col>

      <el-col :span="10">
        <div style="display: flex; float: right">
          <column-config-dialog-vue
            :showSearch.sync="showSearch"
            :columns="tableColumns"
            @queryTable="getList"
          ></column-config-dialog-vue>
        </div>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="specialCertificateList"
      @selection-change="handleSelectionChange"
    >
      <!-- 选中列 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 证书类型 -->
      <el-table-column
        label="证书类型"
        align="center"
        prop="certificateType"
        width="100"
        v-if="
          tableColumns.find((col) => col.prop === 'certificateType').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            dictCache.certificate_type[scope.row.certificateType]
          }}</span>
        </template>
      </el-table-column>

      <!-- 编号 -->
      <el-table-column
        label="编号"
        align="center"
        prop="idNumber"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'idNumber').visible"
      />

      <!-- 姓名 -->
      <el-table-column
        label="姓名"
        align="center"
        prop="studentName"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'studentName').visible"
      />

      <!-- 证件编号 -->
      <el-table-column
        label="证件编号"
        align="center"
        prop="documentNo"
        width="150"
        v-if="tableColumns.find((col) => col.prop === 'documentNo').visible"
      />

      <!-- 性别 -->
      <el-table-column
        label="性别"
        align="center"
        prop="sex"
        width="80"
        v-if="tableColumns.find((col) => col.prop === 'sex').visible"
      />

      <!-- 电话 -->
      <el-table-column
        label="电话"
        align="center"
        prop="phonenumber"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'phonenumber').visible"
      />

      <!-- 作业种类 -->
      <el-table-column
        label="作业种类"
        align="center"
        prop="workCategory"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'workCategory').visible"
      />

      <!-- 作业项目 -->
      <el-table-column
        label="作业项目"
        align="center"
        prop="workProject"
        width="100"
        v-if="tableColumns.find((col) => col.prop === 'workProject').visible"
      />

      <!-- 证书编号 -->
      <el-table-column
        label="证书编号"
        align="center"
        prop="certificateNo"
        width="150"
        v-if="tableColumns.find((col) => col.prop === 'certificateNo').visible"
      />

      <!-- 证书有效期起 -->
      <el-table-column
        label="证书有效期起"
        align="center"
        prop="validityStartTime"
        width="180"
        v-if="
          tableColumns.find((col) => col.prop === 'validityStartTime').visible
        "
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.validityStartTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>

      <!-- 证书有效期止 -->
      <el-table-column
        label="证书有效期止"
        align="center"
        prop="validityEndTime"
        width="180"
        v-if="
          tableColumns.find((col) => col.prop === 'validityEndTime').visible
        "
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validityEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 发证单位 -->
      <el-table-column
        label="发证单位"
        align="center"
        prop="issuingAuthority"
        width="120"
        v-if="
          tableColumns.find((col) => col.prop === 'issuingAuthority').visible
        "
      />

      <!-- 备注 -->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="120"
        v-if="tableColumns.find((col) => col.prop === 'remark').visible"
      />

      <!-- 操作 -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="tableColumns.find((col) => col.prop === 'operation').visible"
      >
        <template slot-scope="scope">
          <!-- 备注 -->
          <el-button size="mini" type="text" @click="handleRemarkRow(scope.row)"
            >备注</el-button
          >
          <!-- 学员通知 -->
          <el-button size="mini" type="text" @click="handleStudentNotice(scope.row)"
            >学员通知</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改特设证书管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div style="padding: 20px; font-size: 14px">
        <!-- 基本信息 -->
        <el-form
          :model="form"
          label-width="80px"
          label-position="left"
          size="small"
        >
          <!-- 第一行：姓名、联系方式、单位 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名">
                <span>{{ form.studentName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式">
                <span>{{ form.phonenumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位">
                <span>{{ form.unit }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：性别、通讯地址、邮政编码 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别">
                <span>{{ form.sex }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="通讯地址">
                <span>{{ form.address }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮政编码">
                <span>{{ form.postalCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第三行：学历、身份证号、作业种类 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="学历">
                <span>{{ form.education }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号">
                <span>{{ form.idCardNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式">
                <span>{{ form.phonenumber }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第四行：作业项目 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="单位">
                <span>{{ form.unit }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业种类">
                <span>{{ form.workCategory }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业项目">
                <span>{{ form.workProject }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 证书信息 -->
        <el-form
          :model="form"
          label-width="100px"
          label-position="left"
          size="small"
          style="margin-top: 20px"
        >
          <el-row :gutter="20">
            <!-- 左侧：证书编号 + 有效期起 -->
            <el-col :span="12">
              <el-form-item label="证书编号">
                <el-input
                  v-model="form.certificateNo"
                  placeholder="请输入证书编号"
                />
              </el-form-item>
              <el-form-item label="证书有效期起">
                <el-date-picker
                  clearable
                  v-model="form.validityStartTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

            <!-- 右侧：发证单位 + 有效期止 -->
            <el-col :span="12">
              <el-form-item label="发证单位">
                <el-input
                  v-model="form.issuingAuthority"
                  placeholder="请输入发证单位"
                />
              </el-form-item>
              <el-form-item label="证书有效期止">
                <el-date-picker
                  clearable
                  v-model="form.validityEndTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 证书信息 -->
    <CertificateInfoDialog
      :visible.sync="dialogVisible"
      :user-info="userInfo"
      @submit="handleCertificateSubmit"
    />
    <!-- 导入证书信息 -->
    <ImportCertificateDialog
      :visible.sync="importVisible"
      @import-success="handleImportSuccess"
    />
    <!-- 备注 -->
    <RemarkDialogVue
      :visible.sync="remarkDialogVisible"
      :record-id="currentRecordId"
      :remark-history="remarkList"
      :remark-type="'11'"
    />
    <!-- 学员通知弹窗 -->
      <student-notice-dialog
        :visible.sync="noticeDialogVisible"
        :class-id="currentClassId"
        @notice-sent="handleNoticeSent"
      />
  </div>
</template>

<script>
import {
  listSpecialCertificate,
  getSpecialCertificate,
  delSpecialCertificate,
  addSpecialCertificate,
  updateSpecialCertificate,
  getSpecialList,
} from "@/api/certificate/specialCertificate";
import { listRemarksByParams } from "@/api/training/remarks";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
//导入证书信息
import ImportCertificateDialog from "../../../components/Certificate/specialCertificate/ImportCertificateDialog.vue";
//证书信息
import CertificateInfoDialog from "../../../components/Certificate/specialCertificate/CertificateInfoDialog.vue";
// 备注
import RemarkDialogVue from "../../../components/Certificate/template/RemarkDialog.vue";
import studentNoticeDialog from "@/components/class/studentNoticeDialog.vue";
export default {
  name: "SpecialCertificate",
  dicts: ["certificate_type"],
  components: {
    ColumnConfigDialogVue,
    ImportCertificateDialog,
    CertificateInfoDialog,
    RemarkDialogVue,
    studentNoticeDialog
  },
  data() {
    return {
      recordDto:null,
      currentClassId: '',
      noticeDialogVisible: false,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 特设证书管理表格数据
      specialCertificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateType: null,
        workCategory: null,
        workProject: null,
        certificateNo: null,
        validityStartTime: null,
        validityEndTime: null,
        issuingAuthority: null,
        reviewStatus: null,
        originalAuthority: null,
        originalCertificateNo: null,
        firstIssueDate: null,
        expireDate: null,
        specialCertificateFee: null,
        paymentId: null,
        invoiceId: null,
        uploadExamSystem: null,
        expireReminderDays: null,
        specialCertificateRemark: null,
        createdTime: null,
        updatedTime: null,
      },
      // 表单参数
      form: {
        studentName: "",
        phonenumber: "",
        unit: "",
        sex: "",
        address: "",
        postalCode: "",
        education: "",
        idCardNo: "",
        workCategory: "",
        workProject: "",
        certificateNo: "",
        validityStartTime: null,
        validityEndTime: null,
        issuingAuthority: "",
      },
      // 表单校验
      rules: {},
      // 缓存字典数据
      dictCache: {
        certificate_type: {},
        // review_status: {},
        // registration_method: {},
        // payment_status: {},
        // invoice_status: {},
        // record_status: {},
        // upload_exam_system: {},
      },
      // 列显隐
      tableColumns: [
        { prop: "certificateType", label: "证书类型", visible: true },
        { prop: "idNumber", label: "编号", visible: true },
        { prop: "studentName", label: "姓名", visible: true },
        { prop: "documentNo", label: "证件编号", visible: true },
        { prop: "sex", label: "性别", visible: true },
        { prop: "phonenumber", label: "电话", visible: true },
        { prop: "workCategory", label: "作业种类", visible: true },
        { prop: "workProject", label: "作业项目", visible: true },
        { prop: "certificateNo", label: "证书编号", visible: true },
        { prop: "validityStartTime", label: "证书有效期起", visible: true },
        { prop: "validityEndTime", label: "证书有效期止", visible: true },
        { prop: "issuingAuthority", label: "发证单位", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      //导入证书信息
      importVisible: false,
      //证书信息
      dialogVisible: false,
      userInfo: {
        studentName: " ",
        phonenumber: " ",
        unitName: " ",
        sex: " ",
        address: " ",
        education: " ",
        postcode: " ",
        idNumber: " ",
        unitPhonenumber: " ",
        workCategory: " ",
        workProject: " ",
      },
      //备注
      remarkDialogVisible: false,
      currentRecordId: "",
      remarkList: [], // 存储备注历史
    };
  },
  created() {
    this.getList();
    this.loadDicts();
  },
  methods: {
    async loadDicts() {
      this.dictCache.certificate_type = this.dict.label.certificate_type;

      // this.dictCache.review_status = this.dict.label.review_status;
      // this.dictCache.registration_method = this.dict.label.registration_method;
      // this.dictCache.payment_status = this.dict.label.payment_status;
      // this.dictCache.invoice_status = this.dict.label.invoice_status;
      // this.dictCache.record_status = this.dict.label.record_status;
      // this.dictCache.upload_exam_system = this.dict.label.upload_exam_system;
    },
    /** 查询特设证书管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.certificateType = "1";
      getSpecialList(this.queryParams).then((response) => {
        this.specialCertificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        specialCertificateId: null,
        certificateType: null,
        templateId: null,
        studentId: null,
        projectId: null,
        registrationId: null,
        workCategory: null,
        workProject: null,
        certificateNo: null,
        validityStartTime: null,
        validityEndTime: null,
        issuingAuthority: null,
        reviewStatus: null,
        originalAuthority: null,
        originalCertificateNo: null,
        firstIssueDate: null,
        expireDate: null,
        specialCertificateFee: null,
        paymentId: null,
        invoiceId: null,
        uploadExamSystem: null,
        expireReminderDays: null,
        specialCertificateRemark: null,
        createdTime: null,
        updatedTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.validityStartTime) {
        this.queryParams.createStartTime =
          this.queryParams.validityStartTime[0];
        this.queryParams.createEndTime = this.queryParams.validityStartTime[1];
      }
      if (this.queryParams.validityEndTime) {
        this.queryParams.createStartTime = this.queryParams.validityEndTime[0];
        this.queryParams.createEndTime = this.queryParams.validityEndTime[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.recordDto=selection
      this.ids = selection.map((item) => item.specialCertificateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "特设证书管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const specialCertificateId = row.specialCertificateId || this.ids;
      getSpecialCertificate(specialCertificateId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "特设证书管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.specialCertificateId != null) {
            updateSpecialCertificate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpecialCertificate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const specialCertificateIds = row.specialCertificateId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除特设证书管理编号为"' +
            specialCertificateIds +
            '"的数据项？'
        )
        .then(function () {
          return delSpecialCertificate(specialCertificateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/specialCertificate/export",
        {
          ...this.queryParams,
        },
        `specialCertificate_${new Date().getTime()}.xlsx`
      );
    },

    //特设证书信息handadd
    //证书信息
    openCertificateDialog() {
      // 检查是否有选中数据
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行操作");
        return;
      }

      // 从列表中找到选中的记录
      const selectedRow = this.specialCertificateList.find(
        (item) => item.specialCertificateId === this.ids[0]
      );

      if (selectedRow) {
        // 将选中行的数据映射到 userInfo 对象
        this.userInfo = {
          studentName: selectedRow.studentName || " ",
          phonenumber: selectedRow.phonenumber || " ",
          unitName: selectedRow.unitName || " ",
          sex: selectedRow.sex || " ",
          address: selectedRow.address || " ",
          education: selectedRow.education || " ",
          postcode: selectedRow.postalCode || " ",
          idNumber: selectedRow.idNumber || " ",
          unitPhonenumber: selectedRow.unitPhonenumber || " ",
          workCategory: selectedRow.workCategory || " ",
          workProject: selectedRow.workProject || " ",
        };

        this.dialogVisible = true;
      } else {
        this.$message.warning("未找到选中的记录");
      }
    },
    handleCertificateSubmit(data) {
      console.log("提交的证书数据:", data);
      var params = {
        specialCertificateId: this.ids[0],
        originalCertificateNo: data.originalCertificateNo,
        issuingAuthority: data.issuingAuthority,
        validityStartTime: data.validityStartTime,
        validityEndTime: data.validityEndTime,
      };
      updateSpecialCertificate(params)
        .then((response) => {
          this.$modal.msgSuccess("更新成功");
          this.dialogVisible = false;
          this.getList(); // 刷新列表数据
        })
        .catch((error) => {
          console.error("更新失败:", error);
          this.$modal.msgError("更新失败");
        });
    },
    //导入证书信息
    handleImportCertificate() {
      this.importVisible = true; // 显示导入对话框
    },

    // 处理导入成功事件
    handleImportSuccess(data) {
      this.$message.success("证书信息导入成功");
      this.getList(); // 刷新列表
    },
    handleSyncCertificate() {
      this.$message.info("点击了同步证书信息");
    },

    handleStudentNotice() {
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.studentId !==undefined){
        targetRow =row
      }else{
        targetRow = this.recordDto[0];
        if (!targetRow ) return this.$message.warning('请选择一个学员');
      }
      this.currentClassId=targetRow.trainingClassId+""
      this.noticeDialogVisible =true
    },
    handleNoticeSent() {
      // 通知发送后处理
      this.noticeDialogVisible=false
      this.getList();
    },

    // 备注
    handleRemark() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行备注");
        return;
      }

      const row = this.specialCertificateList.find(
        (item) => item.specialCertificateId === this.ids[0]
      );
      if (!row) return;

      this.currentRecordId = row.specialCertificateId;

      var params = { foreignId: row.specialCertificateId, remarkType: "11" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },
    // 备注行
    handleRemarkRow(row) {
      var params = { foreignId: row.specialCertificateId, remarkType: "11" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },
    handleReviewRegistration() {
      this.$message.info("点击了复审报名");
    },
  },
};
</script>
